package com.example.redistest1.redisTool;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import io.lettuce.core.dynamic.annotation.Command;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
public class RedisTool {
    private final StringRedisTemplate redisTemplate;
    private String PREX_KEY="user";
    private Integer TTL=10;
    private String uID=UUID.randomUUID().toString()+"-";
    private String threadId=Thread.currentThread().getId()+uID;

    public RedisTool(StringRedisTemplate redisTemplate){
        this.redisTemplate=redisTemplate;
    }
    public void set(String key, Object value, Long time, TimeUnit unit){

        RedisData redisData=new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }
    public <R,ID> R queryid(ID id, Class<R>type, Function<ID,R>function){
        String key=PREX_KEY+id;
        String json=redisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json,type);
        }
        if(json!=null){
            return null;
        }
        R r=function.apply(id);
        if(r==null){
            redisTemplate.opsForValue().set(key,"",TTL,TimeUnit.MINUTES);
            return null;
        }
         redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(r),TTL,TimeUnit.MINUTES);
        return r;
    }
    public <R,ID> R add_discount(ID id,Function<R,ID>function){
        return null;
    }
    public boolean trylock(String key,Long time){

       boolean check= redisTemplate.opsForValue().setIfAbsent(key,threadId,time,TimeUnit.SECONDS);
      //  redisTemplate.opsForHash().putIfAbsent(key,threadId,1);
       return check;
    }

    public void unlock(String key){
        if(threadId.equals(redisTemplate.opsForValue().get(key)))
        redisTemplate.delete(key);

    }
}
